package com.example.advice;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/*
*   统一异常处理，捕获所有的异常
* */
@RestControllerAdvice
public class MyExceptionHandler{
    @ExceptionHandler(BlockException.class)
    public Object handleBlockException(BlockException e){
        Map<String, Object> map = new HashMap<>();
        if (e instanceof FlowException){
            // 限流异常
            map.put("code",-1);
            map.put("msg","限流异常");
        } else if (e instanceof DegradeException) {
            // 降级异常
            map.put("code",-2);
            map.put("msg","降级异常");
        } else if (e instanceof ParamFlowException) {
            // 热点异常
            map.put("code",-3);
            map.put("msg","热点异常");
        } else if (e instanceof AuthorityException) {
            // 授权异常
            map.put("code",-4);
            map.put("msg","限授权异常");
        } else if (e instanceof SystemBlockException) {
            // 系统异常
            map.put("code",-5);
            map.put("msg","系统异常");
        }
        return map;
    }
}
